/**
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY. See the GNU General Public License for more details. Copyright (C) 2011 CellObject.net
 */
package net.cellobject.sqlitexmlbrowser.shared;

import java.util.Iterator;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.ide.IDE;

/**
 * Utility class for dealing with editors
 */
public class EditorUtil {
	/**
	 * Open an editor on the first selected element
	 * 
	 * @param page the page in which the editor should be opened
	 * @param selection the selection containing the object to be edited
	 */
	public static void openEditor(final IWorkbenchPage page, final ISelection selection) {
		if (! (selection instanceof IStructuredSelection)) {
			return;
		}
		final Iterator<?> iter = ((IStructuredSelection)selection).iterator();
		if (!iter.hasNext()) {
			return;
		}
		//
		IFile file = null;
		while (iter.hasNext()) {
			final Object elem = iter.next();
			// Adapt the element to a file.
			if (! (elem instanceof IAdaptable)) {
				return;
			}
			file = (IFile) ((IAdaptable)elem).getAdapter(IFile.class);
			//Don't open derived files
			if ( (file != null) && !file.isDerived()) {
				break;//Target file found
			}
		}
		// Open an editor on that file.
		try {
			IDE.openEditor(page, file);
		} catch (final PartInitException e) {
			Logger.logError("Open editor failed: " + file.toString(), e);
		}
	}

	public static IEditorPart openFileInEditor(final IWorkbenchPage page, final IFile file) {
		//Open Java class in Java editor
		try {
			final IEditorPart activeEditor = IDE.openEditor(page, file);
			return activeEditor;
		} catch (final PartInitException e) {
			Logger.logError("Open editor failed: " + file.toString(), e);
		}
		return null;
	}
}
